package demo.android.com.mvpdemo.mvp2.base;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.lang.reflect.Field;

import demo.android.com.mvpdemo.mvp2.inject.InjectPresenter;

/**
 * Created by Vya on 2018/1/4 0004.
 */

public abstract class BaseMvpActivity extends AppCompatActivity implements BaseView {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setViewContent();
        Log.e("wangyan","BaseMvpActivity---->");
        //创建  P,每个子类的P都不一样要交给子类创建
//        mPresenter = createPresenter();
//        mPresenter.attach(this);

        //反射注入Presenter，也可以使用Dagger
        //拿到类的所有属性
        Field[] fields = this.getClass().getDeclaredFields();
        for(Field field : fields){
            InjectPresenter injectPresenter = field.getAnnotation(InjectPresenter.class);
            if(injectPresenter != null){
                Class<? extends BasePresenter> presenterClazz = null;

                    presenterClazz = (Class<? extends BasePresenter>) field.getType();  //强转不报错，是因为泛型擦除的原因
                    if(!BasePresenter.class.isAssignableFrom(presenterClazz)){
                        throw new RuntimeException("No support inject type "+presenterClazz.getName());
                    }


                try {
                    BasePresenter basePresenter = presenterClazz.newInstance();
                    basePresenter.attach(this);

                    //设置
                    field.setAccessible(true);
                    field.set(this,basePresenter);
                } catch (Exception e){

                }
            }
        }

        initView();
        initData();
    }


    protected abstract void setViewContent();
    protected abstract void initView();
    protected abstract void initData();
   // protected abstract P createPresenter();


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mPresenter.detach();
    }

//    public P getPresenter() {
//        return mPresenter;
//    }
}
